package cn.wolfcode.crm.util;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

// 异常处理器
@ControllerAdvice
public class HandlerExceptionUtil {

    // 没有权限
    @ExceptionHandler(UnauthorizedException.class)
    public void handleException (HttpServletResponse resp, HandlerMethod hm, Exception ex, HttpServletRequest req) throws IOException, ServletException {
        ex.printStackTrace(System.out);
        ResponseBody anno = hm.getMethodAnnotation(ResponseBody.class);
        if (anno == null) {
            req.setAttribute("error", ex);
            req.getRequestDispatcher("/WEB-INF/views/nopermission.jsp").forward(req, resp);
            return;
        }
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JsonUtil.parseToString(new JsonResult().mark("您没有权限访问！")));
    }
    // 普通 Exception
    @ExceptionHandler
    public void defaultHandlerException(HttpServletResponse resp, HandlerMethod hm, Exception ex, HttpServletRequest req) throws IOException, ServletException {
        ex.printStackTrace(System.out);
        ResponseBody anno = hm.getMethodAnnotation(ResponseBody.class);
        if (anno == null) {
            req.setAttribute("error", ex);
            req.getRequestDispatcher("/WEB-INF/views/error.jsp").forward(req, resp);
            return;
        }
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JsonUtil.parseToString(new JsonResult().mark(ex.getMessage())));
    }
}
